Lesson 5 - if statements

If statements provide a way of making a decision within code. It will evaluate a conditional expression and if the result is true it will run some code. It can run as many statements as you wish. If statements are also known as selection. The code below demonstrates a if statment. It will output "x is now 10". The code is run because the if statements expression evaluates to true. x has the value of 5 and 5 is greater than 3.


x = 5
if x > 3:
	x = 10
	print "x is now " + str(x)


Selection - Allows decisions to be made in code and will only run if the conditional expression evaluates to true.

Conditional expression - Must evaluate to true of false

Conditional expressions will always use a conditional operator. The code only runs if the expression is true. However it is possible to run specific code if the value is false. The next code example demonstrates this. The expression will evaulate to false and as such the else part will be run. The output, therefore, will be "x is bigger than 5" and "now we know everything about x!". The last print statement is not part of the if statement. This will be explored later.


x = 10
if x < 5:
	print "x is less than 5"
else:
	print "x is bigger than 5"
print "now we know everything about x!"


Else - Part of a if statement which is only run when the expression is false.